<?php

/*
 +-----------------------------------------------------------------------+
 | plugins/sauserprefs/save_sauserprefs.inc                              |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
 |   Save user spamassassin settings to sql in amavisnew-d format        |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Ben Leto                                                      |
 +-----------------------------------------------------------------------+
 | Requires: plugins/sauserprefs/config.inc.php                          |
 +-----------------------------------------------------------------------+

 $Id: $

*/

require_once('plugins/amavisdnewsql/config.inc.php');
global $amavisdnewsql_config;

$amavis_db = new rcube_mdb2($amavisdnewsql_config['db_dsnw'], $amavisdnewsql_config['db_dsnr'], $amavisdnewsql_config['db_persistent']);
$amavis_db->db_connect('r');

// check DB connections and exit on failure
if ($err_str = $amavis_db->is_error()) {
  raise_error(array(
    'code' => 603,
    'type' => 'db',
    'message' => $err_str), FALSE, TRUE);
}

//Make sure users exsist if not create
if(AmavisCheckUserName()){
	
	//Set Policy for SpamAssassin Tag and Kill Levels
	$S_pid  = $_POST['_policyid'];
	$S_tag  = $_POST['_taglvl'];
	$S_kill = $_POST['_killlvl'];
	$S_uid = $_POST['_amavis_uid'];
	
	//Get Amavis username
	if(!preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $_SESSION['username']))
		$S_Ausername = $_SESSION['username'] . $amavisdnewsql_config['df_emaildomain'];
	else
		$S_Ausername = $_SESSION['username'];


	//Check if Deleting Custom Policy
	if($_POST['_policyid_static'] > 7 && ($S_pid < 8 && $S_pid > 0) ){
		//this is a custom policy going to a predefinded policy
		//need to delete the custom policy
		$sql = sprintf("DELETE FROM policy WHERE id = '%d'", mysql_real_escape_string($_POST['_policyid_static']) );
		$amavis_db->query($sql);
		$result = $amavis_db->affected_rows();
		if ($result)
			$amavis_db->query("UPDATE policy_id_seq SET id = (id-1)");

		
	}

		
	//Check for Custom Policy
	$sql = sprintf("SELECT id FROM policy WHERE (id > 0 AND id < 8) AND spam_tag2_level = '%d' AND spam_kill_level = '%d' LIMIT 1", mysql_real_escape_string($S_tag), mysql_real_escape_string($S_kill) );
	$sql_result = $amavis_db->query($sql);
	if ($sql_result && $amavis_db->num_rows($sql_result) > 0){
		$sql_arr = $amavis_db->fetch_assoc($sql_result);
		$S_pid = $sql_arr['id'];
	}else{
		//This is a customs policy we set
		//Does it exsist in the policy table?
		if ($S_pid > 7){	
			$sql_result = $amavis_db->query(sprintf("SELECT id FROM policy WHERE id = '%d'", mysql_real_escape_string($S_pid)));
			if ($sql_result && $amavis_db->num_rows($sql_result) > 0){
				$sql = sprintf("UPDATE policy SET spam_tag2_level = '%d',spam_kill_level = '%d' WHERE id = '%d'", mysql_real_escape_string($S_tag), mysql_real_escape_string($S_kill), mysql_real_escape_string($S_pid) );	
				$amavis_db->query($sql);
				$result = $amavis_db->affected_rows();
				if (!$result)		
					$OUTPUT->show_message('can not update custom policy', 'error');
			}
		}else{
			//Custom Policy Does not exsist so we will incriment the seq table and 
			//create a custom entry in the policy table
			$sql_result = $amavis_db->query("SELECT id FROM policy_id_seq LIMIT 1");
			if ($sql_result && $amavis_db->num_rows($sql_result) > 0){
				$sql_arr = $amavis_db->fetch_assoc($sql_result);
				$NEW_pid = $sql_arr['id']+1;
				
				$amavis_db->query("UPDATE policy_id_seq SET id = id+1");
				$result = $amavis_db->affected_rows();
				if (!$result){
					$OUTPUT->show_message('can not update seq id', 'error');	
				}else{
					$sql = sprintf("INSERT INTO policy (`id`, `policy_name`, `virus_lover`, `spam_lover`, `banned_files_lover`, `bad_header_lover`, `bypass_virus_checks`, `bypass_spam_checks`, `bypass_banned_checks`, `bypass_header_checks`, `spam_modifies_subj`, `spam_quarantine_to`, `spam_tag_level`, `spam_tag2_level`, `spam_kill_level`) VALUES ('%d', 'Custom', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'Y', 'spam-quarantine', -999, '%d', '%d')", mysql_real_escape_string($NEW_pid), mysql_real_escape_string($S_tag), mysql_real_escape_string($S_kill));
					$amavis_db->query($sql);
					$result = $amavis_db->affected_rows();
					if (!$result)		
						$OUTPUT->show_message('Error Adding Policy', 'error');
					else
						$S_pid = $NEW_pid;		
				}
			}else{
				$OUTPUT->show_message('Error Getting seq id', 'error');
			}
		}
	
	}
	$sql = sprintf("UPDATE users SET policy_id = '%d' WHERE username = '%s'", mysql_real_escape_string($S_pid),  mysql_real_escape_string($S_Ausername) );
	$amavis_db->query($sql);
	//$amavis_db->query("UPDATE users SET policy_id = '".$S_pid."' WHERE username = '".$S_Ausername."'");
	//$amavis_db->query("UPDATE users SET policy_id = '15' WHERE username = '".$S_Ausername."'");
	$result = $amavis_db->affected_rows();
	if(!$result)
		$OUTPUT->show_message('amavisdnewsqlfailed_pol', 'error');
		
	//Start to build whitelist / blacklist
	$ActionArr = $_POST['_address_rule_act'];
	while (list($key, $action) = each($ActionArr)) {
			
			$SPriority = $_POST['_address_rule_pri'][$key];
			$SAddress = $_POST['_address_rule_value'][$key];
			$Stype = $_POST['_address_rule_field'][$key];
			
			if($action == 'INSERT'){
				$sql = sprintf("INSERT INTO wblist (rid,priority,email,wb) VALUES ('%d','%d','%s','%s')", mysql_real_escape_string($S_uid), mysql_real_escape_string($SPriority), mysql_real_escape_string($SAddress), mysql_real_escape_string($Stype));
				$amavis_db->query($sql);
			}elseif($action == 'DELETE'){
				$sql = sprintf("DELETE FROM wblist WHERE rid = '%d' AND email = '%s' AND	wb = '%s'", mysql_real_escape_string($S_uid),  mysql_real_escape_string($SAddress),  mysql_real_escape_string($Stype) );
				$amavis_db->query($sql);
			}
	}

	$OUTPUT->show_message('amavisdnewsqlchanged', 'confirmation');

}else{
	$OUTPUT->show_message('amavisdnewsqlfailed_nouser', 'error');
}

//$_POST['_taglvl']
//$_POST['_killlvl']

// go to next step
rcmail_overwrite_action('amavisdnewsql');

function LogMe($str){
	//Start to build whitelist / blacklist
	$myFile = "/home/undertoe/webmail/plugins/amavisdnewsql/log.txt";
	$fh = fopen($myFile, 'a') or die("can't open file");
	$stringData = $str . "\n\n";
	fwrite($fh, $stringData);
	fclose($fh);
}
function AmavisCheckUserName(){
	global $amavis_db, $amavisdnewsql_config;
	
	$store_u = $_SESSION['username'];
	if(!preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/', $store_u))
		$store_u = $store_u . $amavisdnewsql_config['df_emaildomain'];

	$sql_result = $amavis_db->query("SELECT * FROM users WHERE username = '". $store_u ."'");
	if ($sql_result && $amavis_db->num_rows($sql_result) > 0){
		return true;
	}else{
		$sql = "INSERT INTO users (priority,policy_id,email,digest,username,retention) VALUES ('7','2','".$store_u."','WD','".$store_u."','14')";
		$amavis_db->query($sql);
		$result = $amavis_db->affected_rows();
		if (!$result){
			return false;
		}else{
			$amavis_db->query("UPDATE users_id_seq SET id = id+1");
			$result = $amavis_db->affected_rows();
			if(!$result)
				return false;
			else
				return true;
		}
	}
}

?>